package com.hee.erp.modules.service.impl;

import com.hee.erp.modules.entity.SysMenu;
import com.hee.erp.modules.mapper.SysMenuMapper;
import com.hee.erp.modules.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hee.erp.vo.MenuNode;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-06-13
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<MenuNode> getMenuList() {

        List<SysMenu> list = this.list();
        List<MenuNode> level0MenuList = this.getListByParentId(list, "0");

        setChildren(list,level0MenuList);
        return level0MenuList;


    }

    private void setChildren(List<SysMenu> list, List<MenuNode> parentMenuList) {
        for (MenuNode menuNode : parentMenuList) {
            List<MenuNode> children = this.getListByParentId(list, menuNode.getId());
            menuNode.setChildren(children);
            if (children.size() > 0) {
                setChildren(list, children);
            }
        }
    }

    public List<MenuNode> getListByParentId(List<SysMenu> list, String parentId) {
        return list.stream().filter(sysMenu -> sysMenu.getParentId().equals(parentId))
                .map(sysMenu -> {
                    MenuNode menuNode = new MenuNode();
                    menuNode.setId(sysMenu.getId());
                    menuNode.setPath(sysMenu.getPath());
                    menuNode.setName(sysMenu.getName());
                    menuNode.setComponent(sysMenu.getComponent());
                    menuNode.setRedirect(sysMenu.getRedirect());

                    MenuNode.MenuNodeMeta menuNodeMeta = new MenuNode.MenuNodeMeta();
                    menuNodeMeta.setTitle(sysMenu.getTitle());
                    menuNodeMeta.setIcon(sysMenu.getIcon());
                    menuNodeMeta.setHideChildrenInMenu(sysMenu.getHideChildrenInMenu());
                    menuNodeMeta.setHideMenu(sysMenu.getHideMenu());
                    menuNodeMeta.setHideBreadcrumb(sysMenu.getHideBreadcrumb());

                    menuNode.setMeta(menuNodeMeta);

                    return menuNode;
                }).collect(Collectors.toList());
    }
}
